package com.hjb.service.controller.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.PageHelper;
import com.hjb.service.Wechat.WechatService;
import com.hjb.service.annotation.LogInfo;
import com.hjb.service.annotation.LogType;
import com.hjb.service.app.BaseAreaService;
import com.hjb.service.app.InstalmentOrderService;
import com.hjb.service.app.SiteCompanyService;
import com.hjb.service.app.SiteUserOrderService;
import com.hjb.service.com.ComLogInfoService;
import com.hjb.service.config.constant.ComLogInfoConstant;
import com.hjb.service.config.constant.ComVerifyCodeConstant;
import com.hjb.service.config.constant.EnumCode;
import com.hjb.service.config.constant.Key;
import com.hjb.service.config.constant.ResultMap;
import com.hjb.service.config.constant.enums.FQorderStatus;
import com.hjb.service.config.constant.enums.FeeType;
import com.hjb.service.config.constant.enums.FirstPayType;
import com.hjb.service.config.constant.enums.PlatformPayType;
import com.hjb.service.config.exception.BusinessException;
import com.hjb.service.domain.InstalmentOrder.InstalmentOrder;
import com.hjb.service.domain.SiteCompany.SiteCompany;
import com.hjb.service.domain.SiteUserOrder.SiteUserOrder;
import com.hjb.service.domain.brokerUser.BrokerUser;
import com.hjb.service.domain.comloginfo.ComLogInfo;
import com.hjb.service.domain.siteuser.SiteUser;
import com.hjb.service.user.SiteUserService;
import com.hjb.service.utils.Calculator;
import com.hjb.service.utils.CalendarUtil;
import com.hjb.service.utils.DateUtil;
import com.hjb.service.utils.Location;
import com.hjb.service.utils.MD5Utils;
import com.hjb.service.utils.MapUtil;
import com.hjb.service.utils.NumberUtil;
import com.hjb.service.utils.RequestUtil;
import com.hjb.service.utils.StringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/** 
* @ClassName    : AppContractController 
* @author       : panxingwu 
* @date         : 2018年1月7日 上午1:30:14 
* @Description  : 合同相关服务接口
*/
@RestController
@RequestMapping("/app/contract")
@Api(value="/app/contract",description="APP端合同管理")
public class AppContractController {
	private Logger log = LoggerFactory.getLogger(AppContractController.class);
    @Value("${jixing.images.path}")
    private String imagesPath;
	@Autowired
	private SiteUserOrderService siteUserOrderService;
	@Autowired
	private ComLogInfoService comLogInfoService;
	@Autowired
	private SiteCompanyService siteCompanyService;
	@Autowired
	private InstalmentOrderService instalmentOrderService;
	@Autowired
	private WechatService wechatService;
	@Autowired
	private BaseAreaService baseAreaService;
	@Autowired
	private SiteUserService siteUserService;
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	
	@LogInfo(logType=LogType.查询,operationContent="创建合同订单")
	@PostMapping("create")
	@ResponseBody
	@ApiOperation(value="创建合同订单", notes="创建合同订单")
	@ApiImplicitParams({ 
		@ApiImplicitParam(paramType = "query", dataType = "String", name = "location", value = "设备信息", required = true,defaultValue="IOS|ios 10|USEF89WEF7923RF923F78263F23")
		})
	public ResponseEntity create(HttpServletRequest request,@RequestBody SiteUserOrder siteUserOrder){
		Map<String, Object> result = MapUtil.getRetMap();
		BrokerUser brokerUser = (BrokerUser) request.getSession().getAttribute(Key.BROKERUSER);
		if(brokerUser==null) {
			result.put(Key.DATA, "false");
			result.put(Key.RESULT_CODE, EnumCode.ERR_NOT_LOGIN.getCode());
			result.put(Key.RESULT_INFO, EnumCode.ERR_NOT_LOGIN.getDesc());
	    	return ResponseEntity.ok(result);
		}	
		//生成合同订单号
		String id = DateUtil.getCurrentDate(DateUtil.Format.yyyyMMddHHmmss)+brokerUser.getId();
		
		/*
		 * 第一步，获取公寓信息，获取分期利率
		 * */
		SiteCompany queryCondation = new SiteCompany();
		queryCondation.setBrokerUserId(brokerUser.getId()+"");
		SiteCompany siteCompany = siteCompanyService.getSiteCompanyByUserId(queryCondation);
		double rate = 0.1;
		
		String feeType = siteUserOrder.getFeeType();//服务费承担方 1:租户承担  2:公寓承担
		String platformPayType = siteUserOrder.getPlatformPayType();//平台给公寓的大款方式:1季付，2半年付，3年付
		switch (platformPayType) {
		case "1":
			rate = siteCompany.getRemark1().doubleValue();//季付利率
			break;
		case "2":
			rate = siteCompany.getRemark4().doubleValue();//半年付利率
			break;
		case "3":
			rate = siteCompany.getRemark7().doubleValue();//年付利率
			break;
		default:
			break;
		}
		
		
		/*
		 * 第二步，生成并保存分期订单
		 * */
		//计算租期
		Date start = siteUserOrder.getStartTime();
		Date end = siteUserOrder.getEndTime();
		int monthOffSet = CalendarUtil.getMonthOffSet(start, end);//租赁月数
		int dayOffSet = 0;
		int payTerm = siteUserOrder.getPayTerm();//分期数
		BigDecimal monthCash = siteUserOrder.getCash();//月租金(单位是分)
		BigDecimal dayCash = Calculator.div(monthCash,28,0);//天租金(每月按28天计算)
		int siteUsertotalAmt = 0;//租户应还款总计
		List<InstalmentOrder> InstalmentOrderList = new ArrayList<InstalmentOrder>();
		if(FeeType.FEETYPE_USER.getValue().equals(feeType)) {
			for (int i =1; i <=payTerm; i++) {
				InstalmentOrder instalmentOrder = new InstalmentOrder();
				String orderId = DateUtil.getCurrentDate(DateUtil.Format.yyyyMMddHHmmss)+brokerUser.getId()+i;
				instalmentOrder.setId(orderId);//主键
				instalmentOrder.setApartmentId(siteCompany.getId()+"");//公寓ID
				instalmentOrder.setOrderId(id);//合同订单号
				instalmentOrder.setOverdueAmt(0);//逾期费用
				instalmentOrder.setRepayDate(CalendarUtil.getDateByAddMonth(start,i));//还款日期
				
				BigDecimal rentCash = null;//每期的租金
				if(i==payTerm) {
					Date monthOffSetLaterDate = CalendarUtil.getDateByAddMonth(start,monthOffSet);//获取最后一期付款的日期
					int surplusDays = CalendarUtil.getDayOffset(monthOffSetLaterDate, end);
					dayOffSet = surplusDays;
					rentCash = Calculator.add(monthCash, Calculator.mul(surplusDays, dayCash));
				}else {
					rentCash = monthCash;
				}
				instalmentOrder.setPrincipalAmt(rentCash.intValue());
				
				int interestAmt = Calculator.mul(rentCash,rate).intValue();//每期的利息
				instalmentOrder.setInterestAmt(interestAmt);
				
				int currTotalAmt = rentCash.intValue()+interestAmt;//每期总金额=租金+利息
				instalmentOrder.setTotalAmt(currTotalAmt);
			
				instalmentOrder.setStatus("0");//0:待审核 1:待还  2:已还  3:逾期 
				instalmentOrder.setOverdueDays(0);//逾期天数
				instalmentOrder.setSiteUserMobile(siteUserOrder.getTenancyMobile());//租户的手机号
				instalmentOrder.setTermNo(i);//当前期数
				instalmentOrderService.saveOrder(instalmentOrder);
				InstalmentOrderList.add(instalmentOrder);
				siteUsertotalAmt+=currTotalAmt;
			}
		}
		
		/*
		 * 第三步，生成并保存合同订单
		 * */
		siteUserOrder.setId(id);
		//初始化状态
		siteUserOrder.setStatus(0);
		//金额转换成分
		siteUserOrder.setCash(monthCash);
		siteUserOrder.setTimeOffset(monthOffSet+","+dayOffSet);
		siteUserOrder.setSiteUsertotalAmt(siteUsertotalAmt);
		siteUserOrder.setGmtCreate(new Date());
		String location = request.getParameter("location");
		//保存合同订单
		siteUserOrder.setGmtCreate(new Date());
		siteUserOrderService.addSiteUserOrder(siteUserOrder);
		
		
		/*
		 * 第三步，保存操作日志
		 * */	
		String ip = RequestUtil.getRemoteAddr(request);
		executorService.execute(new Runnable(){
			@Override
			public void run() {
				//保存记录
				ComLogInfo comLogInfo = new ComLogInfo();
				comLogInfo.setUserId(brokerUser.getId().longValue());
				comLogInfo.setEventType(ComLogInfoConstant.EVENT_TYPE.add_siteuserorder.getType());
				comLogInfo.setSuccess(ComLogInfoConstant.SUCCESS.YES.getCode());
				comLogInfo.setDescription("成功");
				comLogInfo.setOperateTime(new Date());
				Map<String,String> map = Location.getLocation(location);
				Integer channel = ComVerifyCodeConstant.CodeChannel.web.getV();
				if(map.get(Location.SYS_TYPE).contains("IOS")) {
					channel = ComVerifyCodeConstant.CodeChannel.ios.getV();
				}
				if(map.get(Location.SYS_TYPE).contains("ANDROID")) {
					channel = ComVerifyCodeConstant.CodeChannel.android.getV();
				}				
				comLogInfo.setChannel(channel);
				comLogInfo.setIp(ip);
				comLogInfoService.insertComLogInfo(comLogInfo);
			}
		});
		/*
		 * 第四步，保存一个用户
		 * */
		SiteUser siteUser = siteUserService.getUserByMobileNo(siteUserOrder.getTenancyMobile());
		if(siteUser==null) {
			siteUser = new SiteUser();
			siteUser.setMobile(siteUserOrder.getTenancyMobile());
			siteUser.setCreateTime(new Date());
			siteUser.setIsBindEmail(0);
			siteUser.setUserStatus(1);
			siteUser.setFlag(0);
			siteUser.setName(siteUserOrder.getTenancyName());
			siteUser.setCardNumber(siteUserOrder.getTenancyIdcard());
			siteUserService.insertSiteUser(siteUser);
		}
		
		Map<String,Object> returnData = new HashMap<String,Object>();
		returnData.put("order",siteUserOrder);
	  	for (Iterator iterator = InstalmentOrderList.iterator(); iterator.hasNext();) {
	  		InstalmentOrder instalmentOrder = (InstalmentOrder) iterator.next();
	  		instalmentOrder.setStatus(FQorderStatus.getConfig(instalmentOrder.getStatus()).get(Key.LABLE));
	  	}
		returnData.put("instalmentOrders", InstalmentOrderList);
		result.put(Key.DATA, returnData);
		result.put(Key.RESULT_CODE, MapUtil.INTF_SUC_CODE);
		result.put(Key.RESULT_INFO, "添加成功");
		return ResponseEntity.ok(result);
	}
	
  @LogInfo(logType=LogType.查询,operationContent="上传文件")
  @PostMapping("upload")
  @ResponseBody
  @ApiOperation(value="上传文件", notes="上传文件")
  @ApiImplicitParams({ 
	@ApiImplicitParam(paramType = "form", dataType = "String", name = "orderId", value = "订单号",defaultValue="20180113120927100000",required = true),
	@ApiImplicitParam(paramType = "form", dataType = "String", name = "mobileNo", value = "手机号",defaultValue="18810526685",required = true),
	@ApiImplicitParam(paramType = "form", dataType = "File", name = "fileContract", value = "合同照片"),
	@ApiImplicitParam(paramType = "form", dataType = "File", name = "fileRenter", value = "租户证件照"),
	@ApiImplicitParam(paramType = "form", dataType = "File", name = "fileHouse", value = "房产证照片")
	})
  public ResponseEntity upload(MultipartHttpServletRequest request) throws IOException, Exception {
	Map<String,Object> result = new HashMap<String,Object>();
	BrokerUser brokerUser = (BrokerUser) request.getSession().getAttribute(Key.BROKERUSER);
	if(brokerUser==null) {
		result.put(Key.DATA, "false");
		result.put(Key.RESULT_CODE, EnumCode.ERR_NOT_LOGIN.getCode());
		result.put(Key.RESULT_INFO, EnumCode.ERR_NOT_LOGIN.getDesc());
    	return ResponseEntity.ok(result);
	}	  
	String doc = "https://image.houseguanjia.com"+imagesPath;
	String orderId = request.getParameter("orderId");
	String mobileNo = request.getParameter("mobileNo");
	//查询订单信息
	SiteUserOrder updateOrder = new SiteUserOrder();
	updateOrder.setId(orderId);  
    String resultCode = "200";
    String resultMsg = "上传成功";
    
	String fileName = "";
	MultipartFile contract_file = ((MultipartHttpServletRequest) request).getFile("fileContract");
	if(contract_file==null) {
		resultCode = "201";
		resultMsg = "合同照片为空";
	}else {
		fileName = getFileName(contract_file.getOriginalFilename());
		uploadFile(contract_file.getBytes(), imagesPath, fileName);
		updateOrder.setOrderUrl(doc+fileName);
	}
	
	MultipartFile renter_file = ((MultipartHttpServletRequest) request).getFile("fileRenter");
	if(renter_file!=null) {
		fileName = getFileName(renter_file.getOriginalFilename());
		uploadFile(renter_file.getBytes(), imagesPath, fileName);
		updateOrder.setOwnerUrl(doc+fileName);
	}
	
	
	MultipartFile house_file = ((MultipartHttpServletRequest) request).getFile("fileHouse");
	if(house_file!=null) {
		fileName = getFileName(house_file.getOriginalFilename());
		uploadFile(house_file.getBytes(), imagesPath, fileName);
		updateOrder.setHouseUrl(doc+fileName);
	}
	
	
	MultipartFile agent_file = ((MultipartHttpServletRequest) request).getFile("fileAgent");
	if(agent_file!=null) {
		fileName = getFileName(agent_file.getOriginalFilename());
		uploadFile(agent_file.getBytes(), imagesPath, fileName);
		updateOrder.setAgentUrl(doc+fileName);
	}
	
	if(mobileNo==null||"".equals(mobileNo)) throw new BusinessException(EnumCode.ERR_NONE_MOBILENO);
	if(orderId==null||"".equals(orderId)) throw new BusinessException(EnumCode.ERR_NONE_ORDERID);
	log.info("生成二维码图片");
	String imageUrl= wechatService.getErweimaTicket(mobileNo);//调用微信生成二维码
	log.info("生成二维码图片：url="+imageUrl);
	updateOrder.setQrcodeUrl(imageUrl);
	
    siteUserOrderService.updateOrder(updateOrder);
    result.put(Key.RESULT_CODE, resultCode);
    result.put(Key.RESULT_INFO, resultMsg);
    result.put(Key.DATA, updateOrder);
    return ResponseEntity.ok(result);
  }
  
  /** 
* @Title      :querOrder 
* @param      :@param request
* @param      :@return
* @param      :@throws IOException
* @param      :@throws Exception 
* @return     :ResponseEntity 
* @Description:查询订单列表
*/
  @LogInfo(logType=LogType.查询,operationContent="查询订单列表")
  @PostMapping("querOrderList")
  @ResponseBody
  @ApiOperation(value="查询订单列表", notes="查询订单列表")
  @ApiImplicitParams({ 
	@ApiImplicitParam(paramType = "form", dataType = "String", name = "keyWords", value = "搜索关键字",defaultValue="",required = false),
	@ApiImplicitParam(paramType = "form", dataType = "String", name = "orderStatus", value = "订单状态",defaultValue="",required = false),
	@ApiImplicitParam(paramType = "form", dataType = "String", name = "orderType", value = "订单类型",defaultValue="",required = false),
	@ApiImplicitParam(paramType = "form", dataType = "String", name = "pageNum", value = "页码",defaultValue="1",required = true),
	@ApiImplicitParam(paramType = "form", dataType = "String", name = "pageSize", value = "页面数量",defaultValue="4",required = true),
	})
  public ResponseEntity querOrderList(HttpServletRequest request) throws IOException, Exception {
	  ResultMap resultMap = new ResultMap();
	  BrokerUser brokerUser = (BrokerUser) request.getSession().getAttribute(Key.BROKERUSER);
		if(brokerUser==null) {
			resultMap.put(Key.DATA, "false");
			resultMap.put(Key.RESULT_CODE, EnumCode.ERR_NOT_LOGIN.getCode());
			resultMap.put(Key.RESULT_INFO, EnumCode.ERR_NOT_LOGIN.getDesc());
	    	return ResponseEntity.ok(resultMap);
		}	
	  Map<String,Object> data = new HashMap<String,Object>();
	  try {
		  String pageNum = request.getParameter("pageNum");
		  String pageSize = request.getParameter("pageSize");
		  if(StringUtil.isEmpty(pageNum)) throw new BusinessException(EnumCode.ERR_NONE_PAGENUM);
		  if(StringUtil.isEmpty(pageSize)) throw new BusinessException(EnumCode.ERR_NONE_PAGESIZE);
		  
		  String keyWords = request.getParameter("keyWords");//搜索关键字
		  String orderType = request.getParameter("orderType");//1:全部  2:逾期
		  String orderStatus = request.getParameter("orderStatus");//订单状态
		  
		  com.github.pagehelper.Page page = PageHelper.startPage(NumberUtil.getInteger(pageNum), NumberUtil.getInteger(pageSize));//设置分页参数
		  boolean isLate = false;
		  if("2".equals(orderType))isLate=true;
		  List<SiteUserOrder> orders = siteUserOrderService.getSiteUserOrderList(keyWords,NumberUtil.getInteger(orderStatus),isLate);
		  if(orders==null||orders.size()==0) {
			  if(pageNum==null) throw new BusinessException(EnumCode.ERR_NONE_ORDER);
		  }
		  if(Long.parseLong(pageNum)>page.getPages()) orders = new ArrayList<SiteUserOrder>();
		  data.put("orders", orders);
		  data.put("totalNum", page.getTotal());
	  }catch(BusinessException e) {
		  resultMap.setResultCode(e.getCode());
		  resultMap.setResultInfo(e.getDesc());
	  }
	  resultMap.put(Key.DATA, data);
	  return ResponseEntity.ok(resultMap);
  }
  
  /** 
  * @Title      :querOrder 
  * @param      :@param request
  * @param      :@return
  * @param      :@throws IOException
  * @param      :@throws Exception 
  * @return     :ResponseEntity 
  * @Description:查询订单详情
  */
    @LogInfo(logType=LogType.查询,operationContent="查询订单详情")
    @PostMapping("querOrderDetail")
    @ResponseBody
    @ApiOperation(value="查询订单详情", notes="查询订单详情")
    @ApiImplicitParams({ 
  	@ApiImplicitParam(paramType = "form", dataType = "String", name = "orderId", value = "订单编号",defaultValue="",required = false),
  	})
    public ResponseEntity querOrderDetail(HttpServletRequest request) throws IOException, Exception {
      Map<String,Object> result = new HashMap<String,Object>();
  	  BrokerUser brokerUser = (BrokerUser) request.getSession().getAttribute(Key.BROKERUSER);
	  if (brokerUser == null) {
			result.put(Key.DATA, "false");
			result.put(Key.RESULT_CODE, EnumCode.ERR_NOT_LOGIN.getCode());
			result.put(Key.RESULT_INFO, EnumCode.ERR_NOT_LOGIN.getDesc());
			return ResponseEntity.ok(result);
	  }   	
      Map<String,Object> data = new HashMap<String,Object>();
  	  String resultCode = EnumCode.SUCCESS.getCode();
  	  String resultMsg = EnumCode.SUCCESS.getDesc();
  	  
  	  //查询订单信息
  	  SiteUserOrder siteUserOrder = siteUserOrderService.getSiteUserOrder(request.getParameter("orderId"));
  	  //查询分期信息
  	  List<InstalmentOrder> instalmentOrders = instalmentOrderService.getOrderList(siteUserOrder.getId());
  	  for (Iterator iterator = instalmentOrders.iterator(); iterator.hasNext();) {
		InstalmentOrder instalmentOrder = (InstalmentOrder) iterator.next();
		instalmentOrder.setStatus(FQorderStatus.getConfig(instalmentOrder.getStatus()).get(Key.LABLE));
	  }
  	  //查询地区
  	  Map<String,Object> area = baseAreaService.getBaseAreasByRegionNo(siteUserOrder.getCityNo());
  	  
  	  //格式化配置
  	  Map<String,String> feeType = FeeType.getConfig(siteUserOrder.getFeeType());
  	  Map<String,String> firstPayType = FirstPayType.getConfig(siteUserOrder.getFirstPaytype());
  	  Map<String,String> paltPayType = PlatformPayType.getConfig(siteUserOrder.getPlatformPayType());
  	  
  	  //格式化租期跨度
  	  String offSet = siteUserOrder.getTimeOffset();
  	  String[] array = offSet.split(",");
  	  if(!array[1].equals("0")) {
  		  offSet = array[0]+"月"+array[1]+"天";
  	  }else {
  		 offSet = array[0]+"月";
  	  }
  	  siteUserOrder.setTimeOffset(offSet);
  	  data.put(Key.AREA, area);
  	  data.put("order", siteUserOrder);//合同订单信息
  	  data.put(Key.FEERECEIVE, feeType);//服务费承担方式
  	  data.put(Key.FIRSTPAYTYPE, firstPayType);//首付方式
  	  data.put(Key.PAYTYPE, paltPayType);//付款方式
  	  data.put("instalmentOrders", instalmentOrders);//分期订单详情
  	  result.put(Key.DATA, data);
  	  result.put(Key.RESULT_CODE, resultCode);
  	  result.put(Key.RESULT_INFO, resultMsg);
  	  return ResponseEntity.ok(result);
    }
    
    /** 
    * @Title      :getWechatImgae 
    * @param      :@return 
    * @return     :String 
    * @Description:生成微信二维码
    */
    @LogInfo(logType=LogType.查询,operationContent="获取微信二维码")
    @PostMapping("getWechatImgae")
    @ResponseBody
    @ApiOperation(value="获取微信二维码", notes="获取微信二维码")
    @ApiImplicitParams({ 
    	@ApiImplicitParam(paramType = "form", dataType = "String", name = "mobileNo", value = "手机号",defaultValue="",required = false),
    	@ApiImplicitParam(paramType = "form", dataType = "String", name = "orderId", value = "订单号",defaultValue="",required = false),
  	})
    public ResponseEntity getWechatImgae(HttpServletRequest request) {
    	Map<String,Object> result = new HashMap<String,Object>();
    	Map<String,String> data = new HashMap<String,String>();
    	String mobileNo = request.getParameter("mobileNo");
    	String orderId = request.getParameter("orderId");
    	result.put(Key.RESULT_CODE, EnumCode.SUCCESS.getCode());
    	result.put(Key.RESULT_INFO, EnumCode.SUCCESS.getDesc());
    	try {
    		if(StringUtil.isEmail(mobileNo)) throw new BusinessException(EnumCode.ERR_NONE_MOBILENO);
    		if(StringUtil.isEmail(orderId)) throw new BusinessException(EnumCode.ERR_NONE_ORDERID);
    		String imageUrl= wechatService.getErweimaTicket(mobileNo);//调用微信生成二维码
    		
    		SiteUserOrder siteUserOrder = new SiteUserOrder();
    		siteUserOrder.setQrcodeUrl(imageUrl);
    		siteUserOrder.setId(orderId);
    		siteUserOrderService.updateOrder(siteUserOrder);//更新二维码地址
    		data.put(Key.URL, imageUrl);
    		result.put(Key.DATA, data);
    	}catch(BusinessException e) {
    		result.put(Key.RESULT_CODE, e.getCode());
    		result.put(Key.RESULT_INFO, e.getDesc());
    	}
    	return ResponseEntity.ok(result);
    }
  
    /** 
    * @Title      :getWechatImgae 
    * @param      :@return 
    * @return     :String 
    * @Description:删除合同
    */
    @LogInfo(logType=LogType.查询,operationContent="删除合同")
    @PostMapping("delOrder")
    @ResponseBody
    @ApiOperation(value="删除合同", notes="删除合同")
    @ApiImplicitParams({ 
    	@ApiImplicitParam(paramType = "form", dataType = "String", name = "orderId", value = "订单号",defaultValue="",required = false)
  	})
    public ResponseEntity delOrder(HttpServletRequest request) {
    	Map<String,Object> result = new HashMap<String,Object>();
		  BrokerUser brokerUser = (BrokerUser) request.getSession().getAttribute(Key.BROKERUSER);
		  if (brokerUser == null) {
				result.put(Key.DATA, "false");
				result.put(Key.RESULT_CODE, EnumCode.ERR_NOT_LOGIN.getCode());
				result.put(Key.RESULT_INFO, EnumCode.ERR_NOT_LOGIN.getDesc());
				return ResponseEntity.ok(result);
		  }      	
    	Map<String,String> data = new HashMap<String,String>();
    	String mobileNo = request.getParameter("mobileNo");
    	String orderId = request.getParameter("orderId");
    	result.put(Key.RESULT_CODE, EnumCode.SUCCESS.getCode());
    	result.put(Key.RESULT_INFO, EnumCode.SUCCESS.getDesc());
    	siteUserOrderService.delSiteUserOrder(orderId);
		result.put(Key.DATA, data);
    	return ResponseEntity.ok(result);
    }    
    
    @LogInfo(logType=LogType.查询,operationContent="获取租赁期数")
    @PostMapping("getTerms")
    @ResponseBody
    @ApiOperation(value="获取租赁期数", notes="获取租赁期数")
    @ApiImplicitParams({ 
    	@ApiImplicitParam(paramType = "form", dataType = "String", name = "startDate", value = "起租日",defaultValue="2018-02-01",required = true),
    	@ApiImplicitParam(paramType = "form", dataType = "String", name = "endDate", value = "截止日",defaultValue="2018-05-10",required = true)
  	})
    public ResponseEntity getTerms(HttpServletRequest request,
	        @RequestParam(value = "startDate",required = true)String startDate,
	        @RequestParam(value = "endDate",required = true)String endDate) throws ParseException {
    	Map<String,Object> result = new HashMap<String,Object>();
		BrokerUser brokerUser = (BrokerUser) request.getSession().getAttribute(Key.BROKERUSER);
		if(brokerUser==null) {
			Map<String,Object> list = new HashMap<String,Object>();
			List<Integer> terms = new ArrayList<Integer>();
			list.put(Key.TERMS, terms);
			result.put(Key.DATA, list);
			result.put(Key.RESULT_CODE, EnumCode.ERR_NOT_LOGIN.getCode());
			result.put(Key.RESULT_INFO, EnumCode.ERR_NOT_LOGIN.getDesc());
	    	return ResponseEntity.ok(result);
		}
		
		SiteCompany queryCondation = new SiteCompany();
		queryCondation.setBrokerUserId(brokerUser.getId()+"");
		SiteCompany siteCompany = siteCompanyService.getSiteCompanyByUserId(queryCondation);
		Integer retainage_paytype = siteCompany.getRetainagePaytype();
		if(retainage_paytype==null) retainage_paytype = 2;
		
		Map<String,Object> termMap = new HashMap<String,Object>();
		List<Integer> terms = new ArrayList<Integer>();
		Date start = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
		Date end = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
		int monthOffSet = CalendarUtil.getMonthOffSet(start, end);//租赁月数
		if(monthOffSet<=0) {
			terms.add(1);
		}else {
			Date monthOffSetLaterDate = CalendarUtil.getDateByAddMonth(start,monthOffSet);//获取最后一期付款的日期
			int surplusDays = CalendarUtil.getDayOffset(monthOffSetLaterDate, end);
			if(surplusDays==0) {
				terms.add(monthOffSet);
			}else {
				if(retainage_paytype==2) terms.add(monthOffSet);
				if(retainage_paytype==1) {
					terms.add(monthOffSet);
					terms.add(monthOffSet+1);
				}
			}
		}
		termMap.put(Key.TERMS, terms);
		result.put(Key.DATA, termMap);
		result.put(Key.RESULT_CODE, "200");
		result.put(Key.RESULT_INFO, "成功");
    	return ResponseEntity.ok(result);
    }   
    
	@LogInfo(logType=LogType.查询,operationContent="修改合同订单")
	@PostMapping("modify")
	@ResponseBody
	@ApiOperation(value="修改合同订单", notes="修改合同订单")
	@ApiImplicitParams({ 
		@ApiImplicitParam(paramType = "query", dataType = "String", name = "location", value = "设备信息", required = true,defaultValue="IOS|ios 10|USEF89WEF7923RF923F78263F23")
		})
	public ResponseEntity modify(HttpServletRequest request,@RequestBody SiteUserOrder siteUserOrder){
		Map<String, Object> result = MapUtil.getRetMap();  
		BrokerUser brokerUser = (BrokerUser) request.getSession().getAttribute(Key.BROKERUSER);
		  if (brokerUser == null) {
				result.put(Key.DATA, "false");
				result.put(Key.RESULT_CODE, EnumCode.ERR_NOT_LOGIN.getCode());
				result.put(Key.RESULT_INFO, EnumCode.ERR_NOT_LOGIN.getDesc());
				return ResponseEntity.ok(result);
		  }  
		String siteUserOrderId = siteUserOrder.getId();
		/*
		 * 第一步，获取公寓信息，获取分期利率
		 * */
		SiteCompany queryCondation = new SiteCompany();
		queryCondation.setBrokerUserId(brokerUser.getId()+"");
		SiteCompany siteCompany = siteCompanyService.getSiteCompanyByUserId(queryCondation);
		double rate = 0.1;
		
		String feeType = siteUserOrder.getFeeType();//服务费承担方 1:租户承担  2:公寓承担
		String platformPayType = siteUserOrder.getPlatformPayType();//平台给公寓的大款方式:1季付，2半年付，3年付
		switch (platformPayType) {
		case "1":
			rate = siteCompany.getRemark1().doubleValue();//季付利率
			break;
		case "2":
			rate = siteCompany.getRemark4().doubleValue();//半年付利率
			break;
		case "3":
			rate = siteCompany.getRemark7().doubleValue();//年付利率
			break;
		default:
			break;
		}
		
		
		/*
		 * 第二步，生成并保存分期订单
		 * */
		//计算租期
		Date start = siteUserOrder.getStartTime();
		Date end = siteUserOrder.getEndTime();
		int monthOffSet = CalendarUtil.getMonthOffSet(start, end);//租赁月数
		int dayOffSet = 0;//剩余天数
		int payTerm = siteUserOrder.getPayTerm();//分期数
		BigDecimal monthCash = siteUserOrder.getCash();//月租金(单位是分)
		BigDecimal dayCash = Calculator.div(monthCash,28,0);//天租金(每月按28天计算)
		
		int siteUsertotalAmt = 0;//租户应还款总计
		List<InstalmentOrder> InstalmentOrderList = new ArrayList<InstalmentOrder>();
		instalmentOrderService.delete(siteUserOrderId);//先删除全部合同订单
		if(FeeType.FEETYPE_USER.getValue().equals(feeType)) {
			for (int i =1; i <=payTerm; i++) {
				InstalmentOrder instalmentOrder = new InstalmentOrder();
				String orderId = DateUtil.getCurrentDate(DateUtil.Format.yyyyMMddHHmmss)+brokerUser.getId()+i;
				instalmentOrder.setId(orderId);//主键
				instalmentOrder.setApartmentId(siteCompany.getId()+"");//公寓ID
				instalmentOrder.setOrderId(siteUserOrderId);//合同订单号
				instalmentOrder.setOverdueAmt(0);//逾期费用
				instalmentOrder.setRepayDate(CalendarUtil.getDateByAddMonth(start,i-1));//还款日期
				
				BigDecimal rentCash = null;//每期的租金
				if(i==payTerm) {
					Date monthOffSetLaterDate = CalendarUtil.getDateByAddMonth(start,monthOffSet);//获取最后一期付款的日期
					int surplusDays = CalendarUtil.getDayOffset(monthOffSetLaterDate, end);
					dayOffSet = surplusDays;
					rentCash = Calculator.add(monthCash, Calculator.mul(surplusDays, dayCash));
				}else {
					rentCash = monthCash;
				}
				instalmentOrder.setPrincipalAmt(rentCash.intValue());
				
				int interestAmt = Calculator.mul(rentCash,rate).intValue();//每期的利息
				instalmentOrder.setInterestAmt(interestAmt);
				
				int currTotalAmt = rentCash.intValue()+interestAmt;//每期总金额=租金+利息
				instalmentOrder.setTotalAmt(currTotalAmt);
			
				instalmentOrder.setStatus("0");//0:待审核 1:待还  2:已还  3:逾期 
				instalmentOrder.setOverdueDays(0);//逾期天数
				instalmentOrder.setSiteUserMobile(siteUserOrder.getTenancyMobile());//租户的手机号
				instalmentOrder.setTermNo(i);//当前期数
				instalmentOrderService.saveOrder(instalmentOrder);//保存合同订单
				InstalmentOrderList.add(instalmentOrder);
				siteUsertotalAmt+=currTotalAmt;
			}
		}
		
		
		/*
		 * 第三步，修改合同订单
		 * */
		siteUserOrder.setId(siteUserOrderId);
		//初始化状态
		siteUserOrder.setStatus(0);
		siteUserOrder.setTimeOffset(monthOffSet+","+dayOffSet);
		//金额转换成分
		siteUserOrder.setCash(monthCash);
		siteUserOrder.setSiteUsertotalAmt(siteUsertotalAmt);
		String location = request.getParameter("location");
		//保存合同订单
		siteUserOrderService.updateOrder(siteUserOrder);
		
		
		/*
		 * 第三步，保存操作日志
		 * */	
		String ip = RequestUtil.getRemoteAddr(request);
		executorService.execute(new Runnable(){
			@Override
			public void run() {
				//保存记录
				ComLogInfo comLogInfo = new ComLogInfo();
				comLogInfo.setUserId(brokerUser.getId().longValue());
				comLogInfo.setEventType(ComLogInfoConstant.EVENT_TYPE.update_siteuserorder.getType());
				comLogInfo.setSuccess(ComLogInfoConstant.SUCCESS.YES.getCode());
				comLogInfo.setDescription("成功");
				comLogInfo.setOperateTime(new Date());
				Map<String,String> map = Location.getLocation(location);
				Integer channel = ComVerifyCodeConstant.CodeChannel.web.getV();
				if(map.get(Location.SYS_TYPE).contains("IOS")) {
					channel = ComVerifyCodeConstant.CodeChannel.ios.getV();
				}
				if(map.get(Location.SYS_TYPE).contains("ANDROID")) {
					channel = ComVerifyCodeConstant.CodeChannel.android.getV();
				}				
				comLogInfo.setChannel(channel);
				comLogInfo.setIp(ip);
				comLogInfoService.insertComLogInfo(comLogInfo);
			}
		});
		Map<String,Object> returnData = new HashMap<String,Object>();
		returnData.put("order",siteUserOrder);
		returnData.put("instalmentOrders", InstalmentOrderList);
		result.put(Key.DATA,returnData);
		result.put(Key.RESULT_CODE, MapUtil.INTF_SUC_CODE);
		result.put(Key.RESULT_INFO, "修改成功");
		return ResponseEntity.ok(result);
	}  
    
	  /** 
	* @Title      :uploadFile 
	* @param      :@param file
	* @param      :@param filePath
	* @param      :@param fileName
	* @param      :@throws Exception 
	* @return     :void 
	* @Description:上传文件
	*/
  private void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
      File targetFile = new File(filePath);  
      if(!targetFile.exists()){    
          targetFile.mkdirs();    
      }       
      FileOutputStream out = new FileOutputStream(filePath+fileName);
      out.write(file);
      out.flush();
      out.close();
  }

	private String getFileName(String fileName) {
		String name = fileName.substring(0, fileName.lastIndexOf("."));
		String temp = fileName.substring(fileName.lastIndexOf("."));
		return StringUtil.getRandomNum(16)+"_"+name+temp;
	}
}
